//var host = "ws://"+window.location.host+"/im-web/websocket";
var host = "wss://"+window.location.host+"/websocket";

var connection = new WebSocket(host); 

var otherUsernameInput = document.querySelector('#callToUsernameInput'); 
var connectToOtherUsernameBtn = document.querySelector('#callBtn'); 

var callPage = document.querySelector('#callPage'); 

var hangUpBtn = document.querySelector('#hangUpBtn');
  
var localVideo = document.querySelector('#localVideo'); 
var remoteVideo = document.querySelector('#remoteVideo'); 

var myConnection;
  
var otherUsername; //对方的名称

createPeerConnection();

var stream;
//handle messages from the server 
connection.onmessage = function (message) { 
   //console.log("Got message", message.data);
   var data = JSON.parse(message.data); 
   otherUsername = data.from;
   
   switch(data.type) { 
      case 1: 
         onOffer(JSON.parse(data.body)); 
         break; 
      case 2: 
         onAnswer(JSON.parse(data.body)); 
         break; 
      case 3: 
         onCandidate(JSON.parse(data.body)); 
         break; 
      default: 
         break; 
   } 
};
  
//when a user logs in 
function createPeerConnection(success) { 
	/*
	const iceServer = {
    	    urls: ["stun:turn.jingcailvtu.org:3478"],
    	    username: "xdy",
    	    credential: "xdy"
    	  };
	*/
	//使用Google的stun服务器
	var iceServer = {
		//"certificates": certq,
		//"iceTransportPolicy":"relay",
	    "iceServers": [
	        {
	    	//"url": "turn:119.29.67.152:3478?transport=tcp",
	    	//"url": "turn:119.29.67.152:3478?transport=tcp",
	    	//"url": "turn:192.168.16.222:3478?transport=tcp",
	    	//"url": "turn:192.168.16.181:3478?transport=tcp",
	    	"urls": ["turn:turn.jingcailvtu.org:3478","turn:turn.jingcailvtu.org:3478?transport=tcp"],
	    	 "username": "xdy",
	         "credential": "xdy"
	    }]
	};
	
	
	try {
		 navigator.mediaDevices.getUserMedia({
		        audio: true,
		        video: true
		    }).then(function(myStream){
		    	
		    	 stream = myStream; 
		         //displaying local video stream on the page 
		         localVideo.srcObject = stream;
				 //localVideo.src = window.URL.createObjectURL(stream);
		    	
		    	  myConnection = new RTCPeerConnection(iceServer); 
		          //console.log(myConnection); 
		          
		          // setup stream listening 
		          myConnection.addStream(stream); 
		          //when a remote user adds stream to the peer connection, we display it 
		          myConnection.onaddstream = function (e) { 
		             remoteVideo.srcObject = e.stream; 
		          };
		          
		      
		          //setup ice handling
		          //when the browser finds an ice candidate we send it to another peer 
		          myConnection.onicecandidate = function (event) { 
		    		console.log("candidate:"+JSON.stringify(event.candidate));
		             if (event.candidate) { 
		                send({ 
		                   type: 3, 
		                   body: JSON.stringify(event.candidate)
		                }); 
		             } 
		      }; 
		    }).catch(e => alert(e));
	} catch (e) {
		alert("getMedia:"+JSON.stringify(e));
	}
};
  
connection.onopen = function () { 
	alert('connect');
   console.log("Connected"); 
};
  
connection.onerror = function (err) { 
	alert('err:'+JSON.stringify(err));
   console.log("Got error", err); 
};
  
// Alias for sending messages in JSON format 
function send(message) { 
   message.to = otherUsername;
   message.from = userid+"";
   var cot = JSON.stringify(message);
  
   connection.send(cot); 
   /*
	$.ajax({
		  type: 'POST',
		  url: '${ctx}/im/sendChatMessage',
		  traditional: true,
		  data: {
			  toId:otherUsername,
			  cot:cot
		  },
		  success: function(data){
			  console.log(data);
		  }
	});
	*/
};



//setup a peer connection with another user 
connectToOtherUsernameBtn.addEventListener("click", function () { 
	otherUsername = otherUsernameInput.value;
	
	
   if (otherUsername.length > 0) { 
	   const offerOptions = {
			    // New spec states offerToReceiveAudio/Video are of type long (due to
			    // having to tell how many "m" lines to generate).
			    // http://w3c.github.io/webrtc-pc/#idl-def-RTCOfferAnswerOptions.
			    offerToReceiveAudio: 1,
			    offerToReceiveVideo: 1
			  };
	   
	   myConnection.createOffer(offerOptions).then(function(offer){
		   send({ 
	           type: 1, 
	           body: JSON.stringify(offer)
	        });
		   myConnection.setLocalDescription(offer); 
	   }, function(e){
		   console.log(e);
	   });
	  
   } 
}); 
 
//when somebody wants to call us 
function onOffer(offer) {
	myConnection.setRemoteDescription(offer);
   //myConnection.setRemoteDescription(new RTCSessionDescription(offer)); 
	
   myConnection.createAnswer(function (answer) { 
      myConnection.setLocalDescription(answer); 
      send({ 
         type: 2, 
         body: JSON.stringify(answer)
      }); 
		
   }, function (error) { 
      alert("oops...error"); 
   }); 
}
  
//when another user answers to our offer 
function onAnswer(answer) { 
   myConnection.setRemoteDescription(answer); 
} 
 
//when we got ice candidate from another user 
function onCandidate(candidate) { 
   myConnection.addIceCandidate(candidate); 
}	


